package com.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class HandlerInterceptor1 implements HandlerInterceptor {

	// 执行时机：Handler执行之前，进入Handler方法之前
	// 使用场景：用户认证、授权（登陆拦截、操作权限的拦截）
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		String requestUri = request.getRequestURI();
		String contextPath = request.getContextPath();
		String url = requestUri.substring(contextPath.length());
		Lg.log("请求 " ,url);
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");// 防止数据传递乱码
		// 对管理后台页面拦截
		//判断除登录外的请求，如果session失效，那么跳转到登录
		/*if (request.getSession().getAttribute("username") == null && !requestUri.contains("login")
				&& !requestUri.contains("app")) {
			//request.getRequestDispatcher("/login").forward(request, response);
			if (request.getHeader("x-requested-with") != null
					&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
				Lg.log("ajax 	请求 return false" ,false);
				*//*response.setHeader("sessionstatus", "timeout");//在响应头设置session状态
				response.sendRedirect("/login");*//*
				//request.getRequestDispatcher("/login").forward(request, response);
				return false;
			}
		}*/
		return true;
	}

	// 执行时机：进入Handler方法，在Handler返回ModelAndView之前执行
	// 使用场景：通过操作modelAndView统一处理一些模型数据或视图页面
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	// 执行时机：Handler执行完成
	// 使用场景 ：统一操作日志记录、异常处理
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
